//路由鉴权：项目当中的路由能不能被访问的设置
import router from '@/router'
//进度条业务包
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from './store'
//获取用户相关的小仓库内部的token数据去判断用户是否登录成功
import useUserStore from './store/modules/user'
import setting from './setting'

//取消进度条的加载效果
nprogress.configure({ showSpinner: false })
let useStore = useUserStore(pinia)

//全局前置守卫
router.beforeEach(async (to, from, next) => {
    //进度条开始
    nprogress.start()
    //获取token判断用户是否登录
    let token = useStore.token
    let username = useStore.username
    if (token) {
        //登录成功，访问login，不能访问，指向首页
        if (to.path == '/login') {
            next({ path: '/' })
        } else {
            //登录成功访问其余路由
            if (username != '请登录') {
                next()
            } else {
                try {
                    //获取用户信息后再放行
                    await useStore.userInfo()
                    next({ ...to })
                } catch (error) {
                    //token过期，获取不到用户信息或者用户手动修改本地存储token
                    await useStore.userLogout()
                    next({ path: '/login', query: { redirect: to.path } })
                }
            }
        }
    } else {
        //用户未登录
        if (to.path == '/login') {
            next()
        } else {
            next({ path: '/login', query: { redirect: to.path } })
        }
    }
})

//全局后置守卫
router.afterEach((to, from) => {
    //进度条结束
    nprogress.done()
    //修改任务栏标题
    document.title = `${setting.title} - ${to.meta.title}`
})
